package packet

import (
	"encoding/binary"
	"io"
)

func ReadPacket(r io.Reader) ([]byte, error) {
	len := make([]byte, 4)
	if _, err := io.ReadFull(r, len); err != nil {
		return nil, err
	}
	body := make([]byte, binary.BigEndian.Uint32(len))
	if _, err := io.ReadFull(r, body); err != nil {
		return nil, err
	}
	return body, nil
}

func WritePacket(w io.Writer, body []byte) error {
	b := make([]byte, 4+len(body))
	binary.BigEndian.PutUint32(b[:4], uint32(len(body)))
	copy(b[4:], body)
	_, err := w.Write(b)
	return err
}
